package com.ruoyi.teamCustomer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.common.DisCustomerBo;
import com.ruoyi.customer.common.DisCustomerRequestBo;
import com.ruoyi.customer.common.DisVo;
import com.ruoyi.customer.service.DisCommonService;
import com.ruoyi.customerPool.domain.vo.UserVo;
import com.ruoyi.customerPool.mapper.CustomerPoolMapper;
import com.ruoyi.enums.BusTypeEnum;
import com.ruoyi.enums.CustomerSort;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.teamCustomer.domain.bo.TeamCustomerBo;
import com.ruoyi.teamCustomer.domain.vo.TeamCustomerVo;
import com.ruoyi.teamCustomer.mapper.TeamCustomerMapper;
import com.ruoyi.teamCustomer.service.ITeamCustomerService;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
@Service
public class TeamCustomerServiceImpl implements ITeamCustomerService {

    private final TeamCustomerMapper teamCustomerMapper;
    private final CustomerPoolMapper customerPoolMapper;
    private final ISysConfigService configService;
    private final DisCommonService disCommonService;

    @Override
    public TableDataInfo<TeamCustomerVo> pageTeamCustomer(TeamCustomerBo bo, PageQuery pageQuery) {
        Page<TeamCustomerVo> result = teamCustomerMapper.selectPageTeamCustomerList(pageQuery.build(),
                this.buildQuery(bo));
        return TableDataInfo.build(result);
    }

    @Override
    public List<TeamCustomerVo> queryInfoList(TeamCustomerBo bo) {
        return teamCustomerMapper.queryInfoList(this.buildQuery(bo));
    }

    @Override
    public List<UserVo> teamUserList(SysUser sysUser) {
        QueryWrapper<SysUser> query = Wrappers.query();
        query.eq("u.del_flag", UserConstants.USER_NORMAL);
        String key = configService.selectConfigByKey(Constants.SALESMAN_ROLEKEY_TYPE);
        query.apply("r.role_key in (" + key + ")");
        query.apply(
                "( d.ancestors like '" + LoginHelper.getLoginUser().getChildren() + "%'" + " OR " + " d.dept_id = "
                        + LoginHelper.getDeptId() + " )");
        query.orderByAsc("(case when d.parent_id = 0 then 1 else 2 end), d.dept_id");
        return customerPoolMapper.getUserList(query);
    }

    /**
     * 客户转移接口
     *
     * @param requestBo
     */
    @Override
    @Transactional
    public void teamCustomerTransferToUser(DisCustomerRequestBo requestBo) {
        // 客户id + 任务id
        List<DisCustomerBo> customerBos = disCommonService.checkDataUser(requestBo, BusTypeEnum.TRANSFER.getCode());
        List<DisVo> disVos = disCommonService.dataDealUser(customerBos, requestBo.getUserBos());

        //Map<String, Object> map = disCommonService.userDataDeal(disVos);
        //List<DisVo> successList = (List<DisVo>) map.get("success");
        disCommonService.disToUser(disVos, BusTypeEnum.TRANSFER.getCode(), LoginHelper.getLoginUser().getNickName(), LoginHelper.getUserId(), LoginHelper.getDeptId());

        //disCommonService.sentInfo(Constants.DIS_MESSAGE, map);

    }

    @Override
    /**
     * 团队转移 部门之间转移
     */
    public void teamCustomerTransferToDept(DisCustomerRequestBo requestBo) {
        List<DisCustomerBo> customerBos = disCommonService.checkDataDept(requestBo, BusTypeEnum.TRANSFER.getCode());
        List<DisVo> disVos = disCommonService.dataDealDept(customerBos, requestBo.getDeptBos());
        disCommonService.disToDept(disVos, BusTypeEnum.TRANSFER.getCode(), LoginHelper.getLoginUser().getNickName(), LoginHelper.getUserId(), LoginHelper.getDeptId());
    }

    private QueryWrapper<TeamCustomerBo> buildQuery(TeamCustomerBo bo) {
        QueryWrapper<TeamCustomerBo> mwq = Wrappers.query();
        mwq.apply(" tc.distribute_dept_id = d.dept_id and su.user_id = tc.task_id ");
        mwq.apply("tc.task_id != -1");
        mwq.eq("tc.deleted", "0");
        mwq.apply(
                "( d.ancestors like '" + LoginHelper.getLoginUser().getChildren() + "%'" + " OR " + " tc.task_id  = "
                        + LoginHelper.getUserId() + " OR " + " d.dept_id = "
                        + LoginHelper.getDeptId() + " )");
        // 处理搜索条件
        mwq.like(StringUtils.isNotBlank(bo.getName()), "tc.name", bo.getName())
                .eq(StringUtils.isNotBlank(bo.getTel()), "tc.tel", bo.getTel())
                .eq(StringUtils.isNotBlank(bo.getCustomerStatus()), "tc.customer_status", bo.getCustomerStatus())
                .eq(StringUtils.isNotBlank(bo.getLevel()), "tc.level", bo.getLevel())
                .eq(StringUtils.isNotBlank(bo.getLoanType()), "tc.loan_type", bo.getLoanType());

        mwq.eq(StringUtils.isNotBlank(bo.getCompanyStatus()), "tc.company_status", bo.getCompanyStatus());
        if (StringUtils.isNotBlank(bo.getStarType())) {
            // 星级提醒 只看账户未冻结的
            mwq.eq("su.locked", 0);
            mwq.eq("tc.is_reviewe", -1);
            // 1星待签约7天
            mwq.apply(Objects.equals("one", bo.getStarType()),
                    "DATEDIFF(DATE_FORMAT(now(), '%Y-%m-%d'), DATE_FORMAT(ifnull(tc.last_remark_time,'2000-12-31 00:00:00'), '%Y-%m-%d')) >= 7 and tc.level = '1' and tc.customer_status = 3 ");
            // 3星1天
            mwq.apply(Objects.equals("three", bo.getStarType()),
                    "DATEDIFF(DATE_FORMAT(now(), '%Y-%m-%d'), DATE_FORMAT(ifnull(tc.last_remark_time,'2000-12-31 00:00:00'), '%Y-%m-%d')) >= 1 and tc.`level` = 3 and tc.customer_status = 3 ");
            // 2,4,5,6星3天
            mwq.apply(Objects.equals("other", bo.getStarType()),
                    "DATEDIFF(DATE_FORMAT(now(), '%Y-%m-%d'), DATE_FORMAT(ifnull(tc.last_remark_time,'2000-12-31 00:00:00'), '%Y-%m-%d')) >= 3 and tc.`level` in (2,4,5,6) and tc.customer_status = 3 ");
            // 新数据
            mwq.apply(Objects.equals("new", bo.getStarType()), "tc.customer_status = 1 and tc.is_new = 1");
        }
        // 未更新天数
        if (StringUtils.isNotBlank(bo.getNotUpdateDay())) {
            mwq.apply("TIMESTAMPDIFF(MINUTE, ifnull(tc.last_remark_time,'2000-12-31 00:00:00'), now()) >" + bo.getNotUpdateDay() + " * 24 * 60");
        }

        // 部门查询
        mwq.eq(bo.getDeptId() != null, "tc.distribute_dept_id", bo.getDeptId());
        if (StringUtils.isNotBlank(bo.getChildrenDept())) {
            String ancestors = bo.getChildrenDept();
            String[] split = ancestors.split(",");
            String deptId = split[split.length - 1];
            mwq.apply("( d.ancestors like '" + bo.getChildrenDept() + "%'" + " OR d.dept_id = " + deptId + " )");
        }

        // 顾问查询
        mwq.like(StringUtils.isNotBlank(bo.getBusName()), "su.nick_name", bo.getBusName());

        mwq.eq(bo.getBusUserId() != null, "tc.task_id", bo.getBusUserId());

        // 批次号
        mwq.like(StringUtils.isNotBlank(bo.getBatchLogo()), "tc.batch_logo", bo.getBatchLogo());


        // 1、进系统时间 2、实际申请时间
        if (StringUtils.isNotBlank(bo.getTimeType()) && StringUtils.isNotBlank(bo.getApplyTimeScope())) {
            String dateStr = "";
            // 今天、昨天、最近7天
            if (Arrays.asList("0", "1", "7").contains(bo.getApplyTimeScope())) {
                dateStr = DateUtils.getTimeBeforeDay(DateUtils.getNowDate(),
                        Integer.parseInt(bo.getApplyTimeScope()), "before");
            }
            // 本月
            if (Objects.equals("30", bo.getApplyTimeScope())) {
                dateStr = DateUtils.getFirstDayOfMonth();
            }
            if (StringUtils.isNotBlank(dateStr)) {
                if (Objects.equals("1", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.create_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.create_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                if (Objects.equals("2", bo.getTimeType())) {
                    if (Arrays.asList("0", "1").contains(bo.getApplyTimeScope())) {
                        mwq.apply("tc.reality_apply_time = DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    } else {
                        mwq.apply("tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
                    }
                }
                mwq.apply(Objects.equals("2", bo.getTimeType()),
                        "tc.reality_apply_time >= DATE_FORMAT('" + dateStr + "', '%Y-%m-%d 00:00:00' )");
            }
            // 自定义时间特殊处理
            if (Objects.equals("99", bo.getApplyTimeScope())) {
                if (Objects.equals("1", bo.getTimeType())) {
                    mwq.ge(bo.getStartTime() != null, "tc.create_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.create_time", bo.getStartTime());
                } else {
                    mwq.ge(bo.getStartTime() != null, "tc.reality_apply_time", bo.getStartTime());
                    mwq.le(bo.getEndTime() != null, "tc.reality_apply_time", bo.getStartTime());
                }
            }
        }

        // 是在审件
        if (Objects.equals("1", bo.getRevieweFlag())) {
            mwq.ne("tc.is_reviewe", -1);
        } else if (Objects.equals("0", bo.getRevieweFlag())) {
            mwq.eq("tc.is_reviewe", -1);
        }
        mwq.eq(StringUtils.isNotBlank(bo.getVip()), "tc.vip", bo.getVip());
        // 房产
        mwq.eq(StringUtils.isNotBlank(bo.getHouse()), "tc.house", bo.getHouse());
        // 公积金
        mwq.eq(StringUtils.isNotBlank(bo.getFund()), "tc.fund", bo.getFund());
        // 备注查询
        mwq.like(StringUtils.isNotBlank(bo.getBz()), "tc.bz", bo.getBz());
        mwq.like(StringUtils.isNotBlank(bo.getEducation()), "tc.education", bo.getEducation());
        // 来源
        mwq.like(StringUtils.isNotBlank(bo.getSource()), "tc.source", bo.getSource());
        // 贷款额度
        String applyMoney = bo.getApplyMoney();
        if (StringUtils.isNotBlank(applyMoney)) {
            String[] split = applyMoney.split("-");
            if (split.length == 2) {
                // 需处理数据格式
                mwq.gt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[0]));
                mwq.lt(StringUtils.isNotBlank(applyMoney), "tc.apply_money", Long.valueOf(split[1]));
            }
        }


        // 渠道id
        String channelId = bo.getChannelId();
        if (StringUtils.isNotBlank(channelId)) {
            channelId = "," + channelId + ",";
            mwq.like("tc.channel_ids", channelId);
        }

        mwq.last(StringUtils.isNotBlank(bo.getSortInfo()), "order by tc." + CustomerSort.of(bo.getSortInfo()) + " " + bo.getSortRule());

        if (!StringUtils.isNotBlank(bo.getSortInfo())) {
            mwq.orderByDesc("tc.create_time");
        }

        return mwq;
    }
}
